package com.anzhen.interview.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhenan on 2017-4-7.
 */
public class PrintNum {

    private volatile int num = 1;

    public static void main(String[] args) throws InterruptedException {
        final PrintNum printNum = new PrintNum();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    printNum.print();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    printNum.print();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        while (printNum.num != 30) {
            TimeUnit.SECONDS.sleep(1L);
        }
    }

    public synchronized void print() throws InterruptedException {
        int index = 0;
        while (this.num<=30) {
            System.out.println(Thread.currentThread().getName() + "---" + this.num);
            this.num++;
            index++;
            if (index == 3) {
                index = 0;
                notify();
                wait();
            }
        }
    }
}
